package com.wuming.common.util;

import java.sql.*;

/**
 * JDBC工具类
 * <p>在各自的电脑上记得修改数据库的URL、用户名、密码!</p>
 *
 * @author 童天宇
 */
public class JDBCUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/health_system?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASSWORD = "tty0726";

    private static Connection connection = null;

    /**
     * 获取数据库连接
     *
     * @return 数据库连接对象
     */
    private static Connection getConnection() {
        try {
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 执行查询语句
     *
     * @param sql    查询语句
     * @param params 参数-与查询语句中的参数顺序对应
     * @return 结果集
     */
    public static ResultSet executeQuery(String sql, Object[] params) {
        ResultSet resultSet = null;
        try {
            connection = getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
            resultSet = preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close();
        }
        return resultSet;
    }

    /**
     * 执行更新语句
     *
     * @param sql    更新语句
     * @param params 参数-与更新语句中的参数顺序对应
     * @return 影响的行数
     */
    public static int executeUpdate(String sql, Object[] params) {
        int result = 0;
        try {
            connection = getConnection();
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setObject(i + 1, params[i]);
            }
            result = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close();
        }
        return result;
    }

    /**
     * 关闭数据库连接
     */
    public static void close() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
